import fg from 'fast-glob';
import fs from 'fs';
import ini from 'ini';
import path from 'path';
import YAML from 'yaml';
import { HostInfoDoc, HostIPCfg, ProjectCfg } from './typings/index.js';

const hudsonRoot = 'D:/tomcat/webapps/hudson';
const jobRoot = path.join(hudsonRoot, 'jobs');

const getProjIniCfg = (projectName: string): ProjectCfg | null => {
    const projIniRoot = 'D:/game_configs';
    const inis = fg.sync(['*.ini', '*.json'], { cwd: projIniRoot, ignore: ['all.svn.json']});
    for (const i of inis) {
        const icontent = fs.readFileSync(path.join(projIniRoot, i), 'utf-8');
        const iext = path.extname(i);
        let iCfg: ProjectCfg;
        if (iext == '.json') {
            iCfg = JSON.parse(icontent);
        } else {
            iCfg = ini.parse(icontent) as ProjectCfg;
        }
        if (iCfg.Project.Name == projectName || iCfg.Project.Name.replaceAll('·', '') == projectName || iCfg.Project.Alias == projectName) {
            iCfg.Project.code = path.basename(i, iext);
            return iCfg;
        }
    }
    return null;
}

const cfgs = await fg('*/config.xml', { cwd: jobRoot });
for (const cfg of cfgs) {
    const jobName = cfg.split('/')[0];

    const cfgFile = path.join(jobRoot, cfg);
    const content = fs.readFileSync(cfgFile, 'utf8');
    const newContent = content.replace('http://192.168.8.27:8080', 'http://builder.fygame.com:8282').replace(/(?<=pcapps\/)\w+/, (s) => {
        const mch = content.match(/<defaultValue>(\S+)-(develop|publish)<\/defaultValue>/);
        if (mch) {
            const projectName = mch[1];
            const type = mch[2];
            const iniCfg = getProjIniCfg(projectName);
            if (iniCfg) {
                let plat: string;
                if (jobName.includes('android')) {
                    plat = 'android';
                } else if (jobName.includes('ios')) {
                    plat = 'ios';
                } else {
                    plat = 'windows';
                }
                return `${iniCfg.Project.code}_${plat}_${type}`; // 替换为ini配置的projec                
            } else {
                console.warn(`[config.xml]未找到项目${projectName}的ini配置`);
                return s;
            }
        } else {
            console.warn(`[config.xml]未找到项目名：${cfg}`);
            return s;
        }

    });
    if (content != newContent) {
        fs.writeFileSync(cfgFile, newContent, 'utf8');
    }
}

const pcapps = path.join(hudsonRoot, 'pcapps');
const subdirs = fs.readdirSync(pcapps);

const movePkg = (p: string, code: string, plat: 'android' | 'ios' | 'windows' | 'webgl' | 'douyin', type: 'develop' | 'publish' | 'qatest', patterns?: string[]) => {
    const pkg = path.join(pcapps, p);
    if (fs.existsSync(pkg)) {
        const newPkg = path.join(pcapps, `${code}_${plat}_${type}`);
        if (!fs.existsSync(newPkg)) {
            fs.mkdirSync(newPkg);
        }
        if (patterns) {
            const files = fg.sync(patterns, { cwd: pkg });
            if (files.length > 0) {
                files.forEach(f => {
                    const src = path.join(pkg, f);
                    const dst = path.join(newPkg, f);
                    if (fs.existsSync(src)) {
                        if (fs.existsSync(dst)) {
                            fs.unlinkSync(src);
                        } else {
                            fs.renameSync(src, dst);
                        }
                    }    
                    const png = f.replace(/\.[^.]+$/, '.png');
                    const srcPng = path.join(pkg, png);
                    const dstPng = path.join(newPkg, png);
                    if (fs.existsSync(srcPng)) {
                        if (fs.existsSync(dstPng)) {
                            fs.unlinkSync(srcPng);
                        } else {
                            fs.renameSync(srcPng, dstPng);
                        }
                    }
                });
            }
        }
    } else {
        console.warn(`pkg ${pkg} not exists, skip`);
    }
}

const hostCfgFile = 'D:/BuildScript/FYMGBuild/config/hostInfo.yml';
const hostInfoContent = fs.readFileSync(hostCfgFile, 'utf-8');
const hostInfoDoc = YAML.parse(hostInfoContent) as HostInfoDoc;
const projects = (hostInfoDoc as HostIPCfg)['192.168.8.27']['项目地址'];
for (const projectName in projects) {
    const iniCfg = getProjIniCfg(projectName);
    if (!iniCfg) {
        console.warn(`未找到项目${projectName}的ini配置`);
        continue;
    }
    const project = projects[projectName];
    if (project.develop?.android?.package) {
        movePkg(project.develop.android?.package, iniCfg.Project.code, 'android', 'develop', ['*.apk', '*.aab', 'apks.txt', 'apklist.html', 'index.html']);
    }
    if (project.develop?.ios?.package) {
        movePkg(project.develop.ios?.package, iniCfg.Project.code, 'ios', 'develop', ['*.ipa', '*.aab', 'apklist.html', 'index.html']);
    }
    if (project.develop?.webgl?.package) {
        movePkg(project.develop.webgl?.package, iniCfg.Project.code, 'webgl', 'develop');
    }
    if (project.develop?.windows?.package) {
        movePkg(project.develop.windows?.package, iniCfg.Project.code, 'windows', 'develop', ['*.zip', 'exeinfo_*.json', 'apks.txt', 'apklist.html', 'index.html']);
    }
    if (project.publish?.android?.package) {
        movePkg(project.publish.android?.package, iniCfg.Project.code, 'android', 'publish', ['*.apk', '*.aab', 'apks.txt', 'apklist.html', 'index.html']);
    }
    if (project.publish?.ios?.package) {
        movePkg(project.publish.ios?.package, iniCfg.Project.code, 'ios', 'publish', ['*.ipa', '*.aab', 'apklist.html', 'index.html']);
    }
    if (project.publish?.webgl?.package) {
        movePkg(project.publish.webgl?.package, iniCfg.Project.code, 'webgl', 'publish');
    }
    if (project.publish?.windows?.package) {
        movePkg(project.publish.windows?.package, iniCfg.Project.code, 'windows', 'publish', ['*.zip', 'exeinfo_*.json', 'apks.txt', 'apklist.html', 'index.html']);
    }
}

for (const subdir of subdirs) {
    const subdirPath = path.join(pcapps, subdir);
    if (fs.statSync(subdirPath).isDirectory()) {
        const files = fs.readdirSync(subdirPath);
        if (files.length == 0) {
            console.log(`delete empty subdir ${subdirPath}`);
            // fs.unlinkSync(subdirPath);
        }
        // else {
        //     console.warn(`subdir ${subdirPath} not empty, skip`);
        // }
    }
}